<?php
namespace app\api\controller;

use app\common\controller\Init;
use app\api\model\Chunks as ChunksModel;
use app\api\model\File as FileModel;
use app\api\model\Folder as FolderModel;

class Upload extends Init
{
    public function index()
    {
        $request = request();
        $FileModel = new FileModel($this->UID);
        $ChunksModel = new ChunksModel($this->UID);
        $FolderModel = new FolderModel($this->UID);
        $Post = input('param.');
        $FileName = $Post['filename'];
        $md5 = $Post['identifier'];
        $filezise = $Post['totalSize'];
        $totalChunks = $Post['totalChunks'];
        $save_path = $Post['save_path'];
        $pdir = $Post['pdir'];
        $pdirId = 0;
        if($pdir != '' && $pdir != '/') {
            $dir = $FolderModel->getByName($pdir);
            $pdirId = $dir['id'];
        }

        $Folder = $FolderModel->getById($pdirId);
        if(!$Folder) {
            error('文件夹不存在',412);
        }

        $save_path_id = $Folder['id'];
        if($save_path !== '') {
            $save_path_id = $FolderModel->createFolder($save_path, $save_path_id);
        }

        // 判断用户容量
        if($FileModel->sotrageCheck($this->UID, $filezise) == false) {
            error('容量不足', 403);
        }

        // 判断该目录下是否有重名文件
        if($FileModel->getFileByDirAndFileName($save_path_id, $FileName) || $FileModel->getFileByDirAndMd5($save_path_id, $md5)) {
            $FileModel->storageCheckOut($this->UID, $filezise); // 设置用户已用容量
            success(['skipUpload'=>true]);
        }

        $uploaded = [];
        if('post' == strtolower($request->method())) {
            $needMerge = $Post['chunkNumber'] == $totalChunks ? true : false;
            // 判断用户容量
            if($FileModel->sotrageCheck($this->UID, $filezise) == false) {
                error('容量不足', 403);
            }

            $FileData = [
                'uid' => $this->UID,
                'file_name' => $FileName,
                'file_size' => $Post['totalSize'],
                'file_md5' => $Post['identifier'],
                'chunk_id' => $Post['chunkNumber'],
                'chunks' => $Post['totalChunks'],
                'current_size' => $Post['currentChunkSize'],
                'chunk_size' => $Post['chunkSize']
            ];
            $file = file_get_contents('php://input');
            $ChunksIsExt = $ChunksModel->AddChunk($FileData);
            if($ChunksIsExt > 0) {
//                $FileModel->storageCheckOut($this->UID, $Post['currentChunkSize']); // 设置用户已用容量
                $is_ = $ChunksModel->SaveChunk($file, $FileData);
                if($is_) {
                    if($needMerge) {
                        $this->merge();
                    }
                    success(['uploaded'=>$uploaded]);
                } else {
                    error('文件保存失败',500);
                }
            } else {
                error('文件添加失败',500);
            }
        }

    }

    public function checkfile()
    {
        $request = request();
        $FileModel = new FileModel($this->UID);
        $ChunksModel = new ChunksModel($this->UID);
        $FolderModel = new FolderModel($this->UID);
        $Post = input('param.');
        $FileName = $Post['filename'];
        $md5 = $Post['identifier'];
        $save_path = $Post['save_path'];
        $filezise = $Post['totalSize'];
        $pdir = $Post['pdir'];
        $pdirId = 0;
        if($pdir != '' && $pdir != '/') {
            $dir = $FolderModel->getByName($pdir);
            $pdirId = $dir['id'];
        }

        $Folder = $FolderModel->getById($pdirId);
        if(!$Folder) {
            error('文件夹不存在',412);
        }

        $save_path_id = $Folder['id'];
        if($save_path !== '') {
            $save_path_id = $FolderModel->createFolder($save_path, $save_path_id);
        }

        // 判断用户容量
        if($FileModel->sotrageCheck($this->UID, $filezise) == false) {
            error('容量不足', 403);
        }

        $uploaded = [];
        if('get' == strtolower($request->method())) {

            // 判断该目录下是否有重名文件
            if($FileModel->getFileByDirAndFileName($save_path_id, $FileName) || $FileModel->getFileByDirAndMd5($save_path_id, $md5)) {
                $FileModel->storageCheckOut($this->UID, $filezise); // 设置用户已用容量
                success(['skipUpload'=>true]);
            }

            $FileIsExt = $FileModel->getFileByMd5($Post['identifier']);
            if($FileIsExt) {
                unset($FileIsExt['id']);
                $FileIsExt['uid'] = $this->UID;
                $FileIsExt['upload_date'] = date('Y-m-d H:i:s');
                $FileIsExt['is_conceal'] = 0;
                $FileIsExt['conceal_time'] = null;
                $FileIsExt['is_del'] = 0;
                $FileIsExt['del_time'] = null;
                $FileIsExt['dir_id'] = $save_path_id;
                $FileIsExt['fileid'] = create_guid();
                $FileModel->SaveFile($FileIsExt);
                $FileModel->storageCheckOut($this->UID, $filezise); // 设置用户已用容量
                success(['skipUpload'=>true]);
            }

            $ChunksIsExt = $ChunksModel->getChunksByMd5($Post['identifier']);
            if($ChunksIsExt && count($ChunksIsExt) > 0) {
                foreach ($ChunksIsExt as $item) {
                    if(!in_array($item['chunk_id'], $uploaded)) {
                        $uploaded[] = $item['chunk_id'];
                    }
                }
                if($Post['totalChunks'] == count($uploaded)) {
                    $this->merge();

                }
                if(count($uploaded) > 0) {
                    success(['uploaded'=>$uploaded]);
                }

            } else {
                // 需要上传
            }
            success(['result'=>true,'uploaded'=>[]]);

        }

    }

    /**
     * 获取用户的上传配置
     */
    public function conf() {
        $data = [
            /*'max' => 1,
            'max_upload' => 1,
            'max_upload_size' => 1024,
            'upload_url' => 'http://pan.zcyso.cc/api/upload',
            'chunkSize' => 1*1024*1024,
            'max_file_size' => 1*1024*1024,
            'zone_size' => 1*1024*1024*/
            'max' => 1,
            'max_upload' => 1,
            'max_upload_size' => 0,
            'upload_url' => 'http://pan.zcyso.cc/api/upload',
            'chunkSize' => 1*1024*1024,
            'max_file_size' => 0,
            'zone_size' => 1*1024*1024*1024*2
        ];

        success($data);
    }

    /**
     * 合并上传的分片文件
     */
    public function merge() {
        $this->checkRequest('post');
        $Post = input('param.');
        $FileName = $Post['filename'];
        $md5 = $Post['identifier'];
        $pdir = $Post['pdir'];
        $fileSize = $Post['totalSize'];
        $save_path = $Post['save_path'];
        $ChunksModel = new ChunksModel($this->UID);
        $FolderModel = new FolderModel($this->UID);
        $FileModel = new FileModel($this->UID);

        if($FileModel->sotrageCheck($this->UID, $fileSize) == false) {
            error('空间不足', 411);
        }
        $pdirId = 0;
        if($pdir != '' && $pdir != '/') {
            $dir = $FolderModel->getByName($pdir);
            $pdirId = $dir['id'];
        }

        $Folder = $FolderModel->getById($pdirId);
        if(!$Folder) {
            error('文件夹不存在',412);
        }

        $save_path_id = $Folder['id'];
        if($save_path !== '') {
            $save_path_id = $FolderModel->createFolder($save_path, $save_path_id);
        }
        $file = $ChunksModel->merge(['file_name' => $FileName, 'md5' => $md5, 'save_path' => $save_path_id]);
        if($file == false) {
            error('文件效验失败',501);
        }
        $FileModel->storageCheckOut($this->UID, $fileSize); // 设置用户已用容量
        success(['file' => $file]);
    }

    public function zone() {
        $this->checkRequest('post');
        $fileName = input('post.fileName');
        $fileSize = input('post.fileSize');
        $pdir = input('post.pdir');
        $save_path = str_replace($fileName, '', input('post.save_path'));
        $FolderModel = new FolderModel($this->UID);
        $FileModel = new FileModel($this->UID);

        if($FileModel->sotrageCheck($this->UID, $fileSize) == false) {
            error('空间不足', 411);
        }
        $pdirId = 0;
        if($pdir != '' && $pdir != '/') {
            $dir = $FolderModel->getByName($pdir);
            $pdirId = $dir['id'];
        }

        $Folder = $FolderModel->getById($pdirId);
        if(!$Folder) {
            error('文件夹不存在',412);
        }

        $save_path_id = $Folder['id'];

        if($save_path != '') {
            $save_path_id = $FolderModel->createFolder($save_path, $save_path_id);
        }

        success(['save_id' => $save_path_id]);

    }
}
